package com.jboost.modules.app.dto.resp;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;

import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 发票信息封装类
 */
@Data
@Slf4j
public class InvoiceInfo {
    private String invoiceType;      // 发票类型
    private String purchaserName;    // 购方名称
    private String sellerName;       // 销方名称
    private String purchaserTaxNo;   // 购方税号
    private String sellerTaxNo;      // 销方税号
    private String invoiceCode;      // 发票代码
    private String invoiceNum;       // 发票号码
    private Long invoiceDate;        // 票据日期
    private String totalAmount;      // 合计金额
    private String taxAmount;        // 税额
    private String amountInFiguers;  // 价税合计

    // 构造函数
    public InvoiceInfo() {}

    // Getter和Setter方法
    // ... 省略getter/setter方法

    @Override
    public String toString() {
        return "InvoiceInfo{" +
                "invoiceType='" + invoiceType + '\'' +
                ", purchaserName='" + purchaserName + '\'' +
                ", sellerName='" + sellerName + '\'' +
                ", purchaserTaxNo='" + purchaserTaxNo + '\'' +
                ", sellerTaxNo='" + sellerTaxNo + '\'' +
                ", invoiceCode='" + invoiceCode + '\'' +
                ", invoiceNum='" + invoiceNum + '\'' +
                ", invoiceDate=" + invoiceDate +
                ", totalAmount='" + totalAmount + '\'' +
                ", taxAmount='" + taxAmount + '\'' +
                ", amountInFiguers='" + amountInFiguers + '\'' +
                '}';
    }

    // 从JSON结果构建InvoiceInfo对象
    public static InvoiceInfo fromJsonResult(JSONObject result) throws ParseException {
        InvoiceInfo info = new InvoiceInfo();

        if (result.has("words_result")) {
            JSONObject wordsResult = result.getJSONObject("words_result");

            info.setInvoiceType(getJsonValueWithEncodingFix(wordsResult, "InvoiceType"));
            info.setPurchaserName(getJsonValueWithEncodingFix(wordsResult, "PurchaserName"));
            info.setSellerName(getJsonValueWithEncodingFix(wordsResult, "SellerName"));
            info.setPurchaserTaxNo(getJsonValueWithEncodingFix(wordsResult, "PurchaserRegisterNum"));
            info.setSellerTaxNo(getJsonValueWithEncodingFix(wordsResult, "SellerRegisterNum"));
            info.setInvoiceCode(getJsonValueWithEncodingFix(wordsResult, "InvoiceCode"));
            info.setInvoiceNum(getJsonValueWithEncodingFix(wordsResult, "InvoiceNum"));
            
            String dateStr = getJsonValueWithEncodingFix(wordsResult, "InvoiceDate");
            if (dateStr != null && !dateStr.isEmpty()) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINESE);
                Date date = formatter.parse(dateStr);
                long timestamp = date.getTime();
                info.setInvoiceDate(timestamp);
            }
            
            info.setTotalAmount(getJsonValueWithEncodingFix(wordsResult, "TotalAmount"));
            info.setTaxAmount(getJsonValueWithEncodingFix(wordsResult, "TotalTax"));
            info.setAmountInFiguers(getJsonValueWithEncodingFix(wordsResult, "AmountInFiguers"));
        }

        return info;
    }

    // 修复编码问题的获取方法
    private static String getJsonValueWithEncodingFix(JSONObject obj, String key) {
        try {
            if (obj.has(key)) {
                String value = obj.getString(key);
                log.info("获取JSON值: {},{}", key,value);
                if (value != null && !value.isEmpty()) {
                    // 检查是否已经是正确的UTF-8字符串
                    if (isValidChineseString(value) && !containsInvalidChars(value)) {
                        return value;
                    }

                    // 尝试修复编码
                    return fixStringEncoding(value);
                }
                return "";
            }
            return "";
        } catch (Exception e) {
            return "";
        }
    }

    // 检查是否包含有效的中文字符
    public static boolean isValidChineseString(String str) {
        // 检查是否包含中文字符
        return str != null && str.matches(".*[\\u4e00-\\u9fa5]+.*");
    }
    
    // 检查是否包含无效字符（如"口"字符、"鈻"字符、"鍙"字符通常是编码错误的标志）
    public static boolean containsInvalidChars(String str) {
        return str != null && (str.contains("口") || str.contains("囗") || str.contains("¿") 
                || str.contains("鈻") || str.contains("") || str.contains("")
                || str.contains("鍙") || str.contains("彛") || str.contains("鍙") || str.contains("彛"));
    }

    // 修复字符串编码
    public static String fixStringEncoding(String value) {
        try {
            // 如果原始字符串已经包含有效的中文字符且不包含乱码字符，直接返回
            if (isValidChineseString(value) && !containsInvalidChars(value)) {
                return value;
            }
            
            // 尝试多种编码转换方式
            // 1. GBK解码
            try {
                byte[] bytes = value.getBytes(StandardCharsets.ISO_8859_1);
                String gbkResult = new String(bytes, "GBK");
                if (isValidChineseString(gbkResult) && !containsInvalidChars(gbkResult)) {
                    return gbkResult;
                }
            } catch (Exception e) {
                // 忽略异常，尝试其他方法
            }
            
            // 2. UTF-8解码
            try {
                byte[] bytes = value.getBytes(StandardCharsets.ISO_8859_1);
                String utf8Result = new String(bytes, StandardCharsets.UTF_8);
                if (isValidChineseString(utf8Result) && !containsInvalidChars(utf8Result)) {
                    return utf8Result;
                }
            } catch (Exception e) {
                // 忽略异常，尝试其他方法
            }
            
            // 3. 处理UTF-8编码错误（针对"鈻枴"类型乱码）
            String utf8Fixed = fixUtf8EncodingPro(value);
            if (isValidChineseString(utf8Fixed) && !containsInvalidChars(utf8Fixed)) {
                return utf8Fixed;
            }
            
            // 4. 处理"鍙ｅ彛"类型乱码
            String otherFixed = fixOtherEncoding(value);
            if (isValidChineseString(otherFixed) && !containsInvalidChars(otherFixed)) {
                return otherFixed;
            }
            
            // 5. 尝试GB2312编码
            String gb2312Fixed = fixGB2312Encoding(value);
            if (isValidChineseString(gb2312Fixed) && !containsInvalidChars(gb2312Fixed)) {
                return gb2312Fixed;
            }
            
            // 如果所有方法都失败，返回原始值
            return value;
        } catch (Exception e) {
            return value;
        }
    }
    
    // 修复UTF-8编码错误（增强版）
    private static String fixUtf8EncodingPro(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        
        try {
            // 尝试多种方式修复UTF-8编码错误
            // 方式1: 直接用UTF-8解码ISO-8859-1字节
            try {
                byte[] bytes = str.getBytes(StandardCharsets.ISO_8859_1);
                String result = new String(bytes, StandardCharsets.UTF_8);
                if (!containsInvalidChars(result)) {
                    return result;
                }
            } catch (Exception e) {
                // 忽略异常
            }
            
            // 方式2: 如果字符串包含乱码特征，尝试特殊处理
            if (str.contains("鈻") || str.contains("")) {
                // 这种情况下，可能是UTF-8字节被错误地以ISO-8859-1解码
                byte[] bytes = str.getBytes(StandardCharsets.ISO_8859_1);
                return new String(bytes, StandardCharsets.UTF_8);
            }
            
            return str;
        } catch (Exception e) {
            return str;
        }
    }
    
    // 其他编码修复方式（包括处理"鍙ｅ彛"类型乱码）
    private static String fixOtherEncoding(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        
        try {
            // 处理"鍙ｅ彛"类型乱码 - 这通常是GB2312/GBK编码被错误地以UTF-8解码导致的
            if (str.contains("鍙") || str.contains("彛") || str.contains("鍙") || str.contains("彛")) {
                // 尝试将字符串按ISO-8859-1编码获取字节，然后按GB2312解码
                byte[] bytes = str.getBytes(StandardCharsets.ISO_8859_1);
                String gb2312Result = new String(bytes, "GB2312");
                if (isValidChineseString(gb2312Result) && !containsInvalidChars(gb2312Result)) {
                    return gb2312Result;
                }
                
                // 如果GB2312不行，尝试GBK
                String gbkResult = new String(bytes, "GBK");
                if (isValidChineseString(gbkResult) && !containsInvalidChars(gbkResult)) {
                    return gbkResult;
                }
                
                // 如果GBK不行，尝试UTF-8
                String utf8Result = new String(bytes, StandardCharsets.UTF_8);
                if (isValidChineseString(utf8Result) && !containsInvalidChars(utf8Result)) {
                    return utf8Result;
                }
            }
            
            // 尝试直接用UTF-8解码
            byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
            String directUtf8 = new String(bytes, StandardCharsets.UTF_8);
            
            // 检查结果是否有效
            if (isValidChineseString(directUtf8) && !containsInvalidChars(directUtf8)) {
                return directUtf8;
            }
            
            return str;
        } catch (Exception e) {
            return str;
        }
    }
    
    // 专门处理GB2312编码问题
    private static String fixGB2312Encoding(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        
        try {
            // 尝试GB2312编码修复
            byte[] bytes = str.getBytes("GB2312");
            String gb2312Result = new String(bytes, StandardCharsets.UTF_8);
            
            // 检查修复结果是否有效
            if (isValidChineseString(gb2312Result) && !containsInvalidChars(gb2312Result)) {
                return gb2312Result;
            }
            
            return str;
        } catch (Exception e) {
            return str;
        }
    }
}